"use client";

import { Loader2, TriangleAlert } from "lucide-react";

import type { UserSummary } from "@/contexts/auth-context";
import { useMeQuery } from "@/hooks/use-me-query";
import { useProjectsQuery } from "@/hooks/use-projects-query";
import type { ProjectSummary } from "@/lib/types";

import { ProjectsSummary } from "./projects-summary";
import { UserSummaryCard } from "./user-summary-card";

interface DashboardViewProps {
  initialUser: UserSummary;
  initialProjects: ProjectSummary[];
}

export function DashboardView({ initialUser, initialProjects }: DashboardViewProps) {
  const { data: user, isLoading: isUserLoading, error: userError } = useMeQuery(initialUser);

  const {
    data: projects,
    isLoading: areProjectsLoading,
    error: projectsError,
  } = useProjectsQuery(initialProjects);

  const isLoading = isUserLoading || areProjectsLoading;
  const hasError = Boolean(userError || projectsError);

  if (isLoading && !user && (!projects || projects.length === 0)) {
    return (
      <div className="flex min-h-[200px] items-center justify-center rounded-lg border border-border bg-card/60">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <>
      {hasError ? (
        <div className="flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3 text-xs text-destructive">
          <TriangleAlert className="h-4 w-4" />
          数据刷新出现问题，请稍后重试。
        </div>
      ) : null}
      <div className="grid gap-6 md:grid-cols-3">
        {user ? <UserSummaryCard user={user} /> : null}
        <ProjectsSummary projects={projects ?? []} />
      </div>
    </>
  );
}
